<template>
    <div class="main-container">
        <div class="main-header">
            <div class="main-header-function">
                <div>
                    <label>Tokens统计</label>
                </div>
            </div>
            <div class="main-header-extra">
                <el-form :inline="true" :model="search" class="demo-form-inline">
                    <el-form-item label="">
                        <el-select v-model="search.agentName" placeholder="Agent搜索">
                            <el-option
                                    v-for="item in search.agents"
                                    :key="item.name"
                                    :label="item.name"
                                    :value="item.name">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="">
                        <el-select v-model="search.modelName" placeholder="模型搜索">
                            <el-option
                                    v-for="item in search.models"
                                    :key="item.modelName"
                                    :label="item.name"
                                    :value="item.modelName">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="">
                        <el-select v-model="search.dateType" placeholder="统计类型">
                            <el-option label="日期" value="DAY"></el-option>
                            <el-option label="月份" value="MONTH"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="">
                        <el-date-picker
                                v-model="search.dateRange"
                                :type="search.dateType == 'DAY' ? 'daterange' : 'monthrange'"
                                :value-format="search.dateType == 'DAY' ? 'yyyy-MM-dd' : 'yyyy-MM'"
                                :picker-options="search.dateType == 'DAY' ? pickerOptionsDay : pickerOptionsMonth"
                                :unlink-panels="true"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="searchEvent">查询</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>

        <div class="main-body">
            <div ref="tokensStatisticsLines" style="width: 100%; height: 100%;"></div>
        </div>
    </div>
</template>

<script>
    import tools from "@/util/Tools";
    import * as echarts from 'echarts/lib/echarts' // ECharts 核心
    import 'echarts/lib/chart/line' // 折线图
    import 'echarts/lib/component/title' // 标题组件
    import 'echarts/lib/component/tooltip' // 提示框组件
    import 'echarts/lib/component/legend' // 图例组件
    import 'echarts/lib/component/grid' // 网格组件

    export default {
        name: "tokensStatistics",
        data() {
            return {
                pickerOptionsDay: {
                    shortcuts: [
                        {
                            text: "最近7天",
                            onClick(picker) {
                                setSearchDateRange(this, 6, picker);
                            }
                        },
                        {
                            text: "最近15天",
                            onClick(picker) {
                                setSearchDateRange(this, 14, picker);
                            }
                        },
                        {
                            text: "最近30天",
                            onClick(picker) {
                                setSearchDateRange(this, 29, picker);
                            }
                        }
                    ]
                },
                pickerOptionsMonth: {
                    shortcuts: [
                        {
                            text: '最近3个月',
                            onClick(picker) {
                                setSearchDateRange(this, 2, picker, true);
                            }
                        },
                        {
                            text: "最近5个月",
                            onClick(picker) {
                                setSearchDateRange(this, 4, picker, true);
                            }
                        },
                        {
                            text: "最近7个月",
                            onClick(picker) {
                                setSearchDateRange(this, 6, picker, true);
                            }
                        }
                    ]
                },
                search: {
                    agentName: "",
                    modelName: "",
                    dateType: "DAY",
                    dateRange: [],
                    models: [],
                    agents: []
                },
                tokensStatistics: null,
                tokensStatisticsChartLines: null
            }
        },
        methods: {
            findModels() {
                tools.get("/model/findAll").then(response => {
                    this.search.models = response.dataList;
                });
            },

            findAgents() {
                tools.get("/agent/findAll").then(response => {
                    this.search.agents = response.dataList;
                });
            },

            tokensUsageStatistics() {
                tools.post("/tokens/usage/statistics", {
                    agentName: this.search.agentName,
                    modelName: this.search.modelName,
                    dateType: this.search.dateType,
                    beginDate: this.search.dateRange[0],
                    endDate: this.search.dateRange[1],
                }).then(response => {
                    this.tokensStatistics = response.data;
                    this.updateTokensStatisticsChartLines();
                });
            },

            searchEvent() {
                if (!this.search.dateRange || this.search.dateRange.length == 0) {
                    this.$message({
                        type: "error",
                        message: "请选择搜索日期范围日期"
                    });
                    return;
                }
                this.tokensUsageStatistics();
            },

            initChart() {
                let ref = this.$refs.tokensStatisticsLines;
                this.tokensStatisticsChartLines = echarts.init(ref);
            },

            updateTokensStatisticsChartLines() {
                this.tokensStatisticsChartLines.setOption(
                    chartOption(
                        this.tokensStatistics.xdata,
                        ["输入", "输出", "总计"],
                        [
                            {
                                name: "输入",
                                data: this.tokensStatistics.input,
                            },
                            {
                                name: "输出",
                                data: this.tokensStatistics.output,
                            },
                            {
                                name: "总计",
                                data: this.tokensStatistics.total,
                            }
                        ]
                    )
                );
                this.tokensStatisticsChartLines.resize();
            },
            handleResize() {
                if (this.tokensStatisticsChartLines) {
                    this.tokensStatisticsChartLines.resize();
                }
            }
        },
        watch: {
            "search.dateType": {
                handler(newVal, oldVal) {
                    this.search.beginDate = "";
                    this.search.endDate = "";
                    this.search.dateRange = []
                },
            }
        },
        mounted() {
            setSearchDateRange(this, 6);
            this.findModels();
            this.findAgents();

            this.$nextTick(() => {
                requestAnimationFrame(() => {
                    this.initChart();
                    this.tokensUsageStatistics();
                });
            });
            window.addEventListener("resize", this.handleResize);
        }
    }

    function setSearchDateRange(that, interval, picker, month) {
        const start = new Date();
        const end = new Date();
        if (month) {
            start.setMonth(start.getMonth() - interval);
        } else {
            start.setTime(start.getTime() - 3600 * 1000 * 24 * interval);
        }
        if (picker) {
            picker.$emit("pick", [start, end]);
        } else {
            that.search.dateRange = [tools.dateFormatYMD(start), tools.dateFormatYMD(end)];
        }
    }

    function chartOption(xAxisData, legendData, yAxisData) {
        let option = {
            xAxis: {
                data: xAxisData,
                boundaryGap: false,
                axisTick: {
                    show: true
                },
                axisLabel: {
                    interval: "auto"
                }
            },
            grid: {
                left: 26,
                right: 40,
                bottom: 20,
                top: 30,
                containLabel: true
            },
            tooltip: {
                trigger: "axis",
            },
            yAxis: {
                axisTick: {
                    show: true
                }
            },
            legend: {
                data: legendData,
            },
            series: []
        };

        for (let data of yAxisData) {
            let series = {
                name: data.name,
                smooth: true,
                type: "line",
                data: data.data,
                animationDuration: 0,
            }
            option.series.push(series);
        }

        option.xAxis.axisLabel = {
            interval: calculateInterval(xAxisData.length),
        }

        function calculateInterval(length) {
            if (length <= 10) return 0;
            if (length <= 30) return 2;
            if (length <= 50) return 4;
            return Math.floor(length / 10);
        }

        return option;
    }

</script>

<style scoped>

</style>
